'use client';

import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Image, Modal, Pagination, Spin, Empty, Typography, Tag, Space, Select, Button } from 'antd';
import { FileImageOutlined, CalendarOutlined, FileTextOutlined, SortAscendingOutlined, SortDescendingOutlined } from '@ant-design/icons';
import AdminLayout from '../AdminLayout';
import styles from './GenerationRecords.module.scss';

const { Title, Text } = Typography;

interface ImageRecord {
  id: string;
  name: string;
  path: string;
  size: number;
  createTime: Date | string;
  imageData: string; // base64编码的图片数据
  mimeType: string; // 图片MIME类型
}

export default function GenerationRecordsPage() {
  const [images, setImages] = useState<ImageRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [isImageZoomed, setIsImageZoomed] = useState(false);
  const [total, setTotal] = useState(0);
  const [sortBy, setSortBy] = useState('createTime');
  const [sortOrder, setSortOrder] = useState('desc');

  // 获取图片记录
  const fetchImageRecords = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: currentPage.toString(),
        pageSize: pageSize.toString(),
        sortBy,
        sortOrder
      });
      
      const response = await fetch(`/api/generation-records?${params}`);
      
      if (!response.ok) {
        throw new Error('获取图片记录失败');
      }

      const data = await response.json();
      setImages(data.images || []);
      setTotal(data.total || 0);
    } catch (error) {
      console.error('获取图片记录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchImageRecords();
  }, [currentPage, pageSize, sortBy, sortOrder]);

  // 处理键盘事件
  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      if (!previewVisible) return;
      
      switch (event.key) {
        case 'Escape':
          setPreviewVisible(false);
          setIsImageZoomed(false);
          break;
        case ' ':
          event.preventDefault();
          handleImageZoom();
          break;
      }
    };

    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, [previewVisible]);

  // 处理图片预览
  const handlePreview = (image: ImageRecord) => {
    // 检查图片数据是否有效
    if (!image.imageData || image.imageData.length === 0) {
      console.error('图片数据为空');
      return;
    }
    
    setPreviewImage(`data:${image.mimeType};base64,${image.imageData}`);
    setPreviewTitle(image.name);
    setPreviewVisible(true);
    setIsImageZoomed(false);
  };

  // 处理图片放大/缩小
  const handleImageZoom = () => {
    setIsImageZoomed(!isImageZoomed);
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 格式化时间
  const formatTime = (date: Date | string): string => {
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    
    // 检查日期是否有效
    if (isNaN(dateObj.getTime())) {
      return '未知时间';
    }
    
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).format(dateObj);
  };

  // 处理排序变化
  const handleSortChange = (newSortBy: string) => {
    if (sortBy === newSortBy) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(newSortBy);
      setSortOrder('desc');
    }
    setCurrentPage(1);
  };

  // 渲染图片卡片
  const renderImageCard = (image: ImageRecord) => (
    <Col xs={12} sm={8} md={6} lg={4} xl={4} key={image.id}>
             <Card
         hoverable
         className={styles.imageCard}
         cover={
           <div 
             className={styles.imageContainer}
             onClick={(e) => {
               e.preventDefault();
               e.stopPropagation();
               handlePreview(image);
             }}
           >
             <Image
               alt={image.name}
               src={`data:${image.mimeType};base64,${image.imageData}`}
               className={styles.image}
               preview={false}
             />
           </div>
         }
         styles={{ body: { padding: '8px' } }}
       >
        <div className={styles.imageInfo}>
          <Text className={styles.imageName} ellipsis={{ tooltip: image.name }}>
            {image.name}
          </Text>
          
          <Space direction="vertical" size={4} className={styles.imageMeta}>
            <div className={styles.metaItem}>
              <FileTextOutlined className={styles.metaIcon} />
              <Text className={styles.metaText}>
                {formatFileSize(image.size)}
              </Text>
            </div>
            
            <div className={styles.metaItem}>
              <CalendarOutlined className={styles.metaIcon} />
              <Text className={styles.metaText}>
                {formatTime(image.createTime)}
              </Text>
            </div>
          </Space>
        </div>
      </Card>
    </Col>
  );

  return (
    <AdminLayout>
      <div className={styles.container}>
        <div className={styles.header}>
          <Title level={2} className={styles.title}>
            <FileImageOutlined className={styles.titleIcon} />
            生成记录
          </Title>
          <div className={styles.headerControls}>
            <div className={styles.sortControls}>
              <Select
                value={sortBy}
                onChange={handleSortChange}
                style={{ width: 120, marginRight: 8 }}
                className={styles.sortSelect}
              >
                <Select.Option value="createTime">创建时间</Select.Option>
                <Select.Option value="name">文件名</Select.Option>
                <Select.Option value="size">文件大小</Select.Option>
              </Select>
              <Button
                type="text"
                icon={sortOrder === 'asc' ? <SortAscendingOutlined /> : <SortDescendingOutlined />}
                onClick={() => {
                  setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                  setCurrentPage(1);
                }}
                className={styles.sortButton}
              />
            </div>
                       <div className={styles.stats}>
             <Tag color="green" className={styles.statTag}>
               总计: {total} 张图片
             </Tag>
           </div>
          </div>
        </div>

        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" />
            <Text className={styles.loadingText}>正在加载图片记录...</Text>
          </div>
        ) : images.length === 0 ? (
          <div className={styles.emptyContainer}>
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="暂无生成记录"
              className={styles.empty}
            />
          </div>
        ) : (
          <>
            <Row gutter={[16, 16]} className={styles.imageGrid}>
              {images.map(renderImageCard)}
            </Row>

            <div className={styles.paginationContainer}>
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                showSizeChanger
                showQuickJumper
                showTotal={(total, range) => 
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                }
                onChange={(page, size) => {
                  setCurrentPage(page);
                  setPageSize(size || 12);
                }}
                onShowSizeChange={(current, size) => {
                  setCurrentPage(1);
                  setPageSize(size);
                }}
                                 pageSizeOptions={['12', '24']}
                className={styles.pagination}
              />
            </div>
          </>
        )}

                 {/* 图片预览模态框 */}
         <Modal
           open={previewVisible}
           title={previewTitle}
           footer={null}
           onCancel={() => {
             setPreviewVisible(false);
             setIsImageZoomed(false);
           }}
           width={isImageZoomed ? "95%" : "80%"}
           className={styles.previewModal}
           destroyOnClose
         >
           <div className={styles.previewContainer}>
             <Image
               alt={previewTitle}
               src={previewImage}
               className={`${styles.previewImage} ${isImageZoomed ? styles.zoomed : ''}`}
               preview={false}
               onClick={handleImageZoom}
             />
           </div>
           <div className={styles.previewHint}>
             <Text className={styles.hintText}>
               点击图片{isImageZoomed ? '缩小' : '放大'} | 空格键切换 | ESC关闭
             </Text>
           </div>
         </Modal>
      </div>
    </AdminLayout>
  );
}
